package com.lebang.controller.sys.cences;

import com.alibaba.fastjson.JSONObject;
import com.lebang.common.Login;
import com.lebang.configuration.datasource.DataSource;
import com.lebang.domain.CencesStoreData;
import com.lebang.domain.TaskRouse;
import com.lebang.example.CencesStoreDataExample;
import com.lebang.model.MyConfig;
import com.lebang.model.cences.TotalCount;
import com.lebang.service.DownAppService;
import com.lebang.service.NewRouseService;
import com.lebang.service.cences.CencesEarnDataService;
import com.lebang.service.sys.DictService;
import com.lebangweb.common.TextUtil;
import com.lebangweb.response.Callback;
import com.lebangweb.response.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * 新手任务
 *
 * @author hwq
 * @date 2020-02-06
 */
@Controller
@RequestMapping("/sys/cencesearndaydata")
public class CencesEarnDataController {
    @Autowired
    private CencesEarnDataService baseService;
    @Autowired
    private DownAppService downAppService;
    @Autowired
    private NewRouseService newRouseService;
    @Autowired
    private DictService dictService;

    @Login
    @GetMapping("/list")
    public String list(Model model, HttpSession session) {
        List<TaskRouse> rouses = newRouseService.selectAll();
        rouses = newRouseService.checkRoot(rouses,session);
        model.addAttribute("item", rouses);
        return "/cencesearndaydata/list";
    }

    @Login
    @GetMapping("/add")
    @DataSource("commonDB")
    public String add(Integer id, Model model) {
        CencesStoreData vo;
        if (id != null) {
            vo = baseService.selectById(id);
        } else {
            vo = new CencesStoreData();
        }
        model.addAttribute("item", vo);
        return "/cencesearnday/edit";
    }

    @Login
    @PostMapping("/edit")
    @ResponseBody
    @DataSource("commonDB")
    public JsonData edit(CencesStoreData vo) {
        if (vo.getId() != null) {
            baseService.updateById(vo);
        } else {
            baseService.insertModel(vo);
        }
        return Callback.success("success", "修改成功");
    }

    /**
     * @param page
     * @param limit
     * @param star
     * @param end
     * @param appStore
     * @param category 1新用户0老用户2全部
     * @return
     */
    @PostMapping("/page")
    @ResponseBody
    @DataSource("commonDB")
    @Login
    public HashMap newlist(String likeBrand,Long page, Integer limit, Integer star, Integer end, String appStore, int category, int type) {
        // limit=limit-1;
        HashMap map = new HashMap(1);
        CencesStoreDataExample example = new CencesStoreDataExample();
        CencesStoreDataExample.Criteria c = example.createCriteria();
        example.setOffset((page - 1) * limit);
        example.setLimit(limit);
        example.setOrderByClause("time desc");
        c.andAppIdEqualTo(MyConfig.getEnv());
        if (star != null && end != null) {
            c.andTimeBetween(star, end);
        }

        if(!TextUtil.isEmpty(likeBrand)){
            c.andBrandLike(likeBrand+"%");
            appStore=null;
        }else {
            likeBrand=null;
            if (!TextUtil.isEmpty(appStore)) {
                c.andBrandEqualTo(appStore);
            }else {
                appStore=null;
            }
        }
        map.put("count", baseService.countByExample(example));
        map.put("code", 0);
        List<CencesStoreData> masters = baseService.selectByExample(example);
        CencesStoreData vo = baseService.sumData(star, end, appStore, category, type,likeBrand);
        if(null!=vo){
            vo.setTime(-1);
            masters.add(vo);
        }
        map.put("data", masters);
        return map;
    }

    @Login
    @PostMapping("/lastCheck")
    @ResponseBody
    public String cen(String date) {
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate end = LocalDate.parse(date, fmt);
        baseService.starDataInit(LocalDateTime.of(end.plusDays(1), LocalTime.MIN));
        return "success";
    }

    @Login
    @PostMapping("/delete")
    @DataSource("commonDB")
    @ResponseBody
    public JsonData delete(Integer id) {

        baseService.deleteByTime(baseService.selectById(id).getTime());
        return Callback.success("success", "删除成功");
    }

    @Login
    @PostMapping("/sumcount")
    @ResponseBody
    public JSONObject sumcount(Integer id,
                             @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime star,
                             @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime end,


                             String appStore) {
        JSONObject jsonObject=new JSONObject();
        List<TotalCount> list = new ArrayList<>();
        LocalDateTime dateTime = LocalDateTime.of(2020, 3, 24, 0, 0, 0, 0);

        int between = end.getDayOfYear() - star.getDayOfYear();
        if (TextUtil.isEmpty(appStore)) {
            appStore = null;
        }
        //最大次数
        int count = dictService.selectIntByKeyName("csj_down_success_count") + dictService.selectIntByKeyName("csj__look_success_count") + 7;

        for (int i = 1; i < count; i++) {
            TotalCount totalCount = baseService.selectData(star, end, appStore, i, between);
            list.add(totalCount);
        }

      // List<TaskRouseModel>
        jsonObject.put("code",0);
        jsonObject.put("data",list);
        jsonObject.put("count",list.size());
        return jsonObject;
    }

    @Login
    @GetMapping("/apru")
    public String apru(Model model, HttpSession session) {
        List<TaskRouse> rouses = newRouseService.selectAll();
        rouses = newRouseService.checkRoot(rouses,session);
        model.addAttribute("item", rouses);
        return "/cencesearnday/data";
    }


}
